package drds.server.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import drds.server.config.ErrorCode;
import drds.server.datasource.IConnectionHolder;
import drds.server.net.packet.ErrorPacket;
import drds.server.server.Session;
import drds.server.server.SessionContext;

public class CommitNodeHandler extends HandlerAdapter {
	private static final Logger LOGGER = LoggerFactory.getLogger(CommitNodeHandler.class);
	private final Session session;

	public CommitNodeHandler(Session session) {
		this.session = session;
	}

	/**
	 * 提交事务
	 */
	public void commit(IConnectionHolder connectionHolder) {
		connectionHolder.setHandler(CommitNodeHandler.this);
		/**
		 * 如果绑定的连接关闭或者退出则抛出异常
		 */
		boolean isClosed = connectionHolder.isClosedOrQuit();
		if (isClosed) {
			session.getSessionContext().writeErrorMessage(ErrorCode.ER_UNKNOWN_ERROR, "receive commit,but find backend con is closed or quit");
			LOGGER.error(connectionHolder + "receive commit,but fond backend con is closed or quit");
			return;
		}
		connectionHolder.commit();
		return;
	}

	/**
	 * 提交成功
	 */
	@Override
	public void okResponse(IConnectionHolder connectionHolder, byte[] okBytes) {
		session.clearResources(false);
		SessionContext sessionContext = session.getSessionContext();
		sessionContext.write(okBytes);
	}

	/**
	 * 提交失败
	 */
	@Override
	public void errorResponse(IConnectionHolder connectionHolder, byte[] errorBytes) {
		ErrorPacket errorPacket = new ErrorPacket();
		errorPacket.read(errorBytes);
		String errorMessage = new String(errorPacket.errorMessage);
		session.getSessionContext().setTransactionInterruptStatus(errorMessage);
		errorPacket.write(session.getSessionContext());

	}

}
